package webx.actions;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.search.ui.ISearchQuery;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.text.TextSearchQueryProvider;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.texteditor.ITextEditor;

@SuppressWarnings("restriction")
class MySelectListener implements ISelectionListener{

	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		// TODO Auto-generated method stub
		//System.out.println("selection:"+selection.toString());
		System.out.println("part:"+part.getTitleToolTip());
	}
	
}

class FindRun1 extends Thread{
	static String openfile="";
	
	static String bookmark = ""; 
	
	static String bookmarkfile = "";
	
	static String scope="";
	
	static String string = "";
	
	int port = 2017;

	private ServerSocket ser;
	
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void run() {
		try {
			ser = new ServerSocket(port);
		}catch (IOException e) {
			try {
				if(ser!=null)
				ser.close();
			} catch (Exception e1) {e1.printStackTrace();}
		}
		Display.getDefault().syncExec(new Runnable() {
	         public void run() {
				try{
					ISelectionService selecttion = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService();
					selecttion.addSelectionListener(new MySelectListener());
				}catch(Throwable e){
					e.printStackTrace();
				}
	         }
		});    
		while(true){
			InputStream ins = null;
			Socket explor = null;
			OutputStream os = null;
			try {
				if(ser == null) break;
				
				System.out.println("1111url get:");
				explor = ser.accept();
				ins = explor.getInputStream();
				os = explor.getOutputStream();
				
				
				System.out.println(ins.available());
				int xx= ins.available()==0?9000:ins.available(); 
				
				byte[] httprequest_data = new byte[xx];
				ins.read(httprequest_data);
				String rstr = new String(httprequest_data,"UTF-8");
//				BufferedReader br = new BufferedReader(new InputStreamReader(ins));
//				int count=0;Map req = new HashMap();
//				while(true){
//					count++;
//					System.out.println("第"+count+"次读:");
//					String line = br.readLine();
//					if(line==null){
//						break;
//					}
//					if(count==1){
//						if(line.startsWith("GET")){
//							System.out.println("GET:"+line);
//							String uri = line.split(" ")[1];
//							String[] patt = uri.split("\\?");
//							if(patt[0].equals("/editor.html")){
//								File editor = new File(sssex.Activator.plugin_path+"kindeditor-4.1.10/examples/default.html");
//								byte[] editorb = new byte[(int)editor.length()];
//								FileInputStream fis = new FileInputStream(editor);
//								fis.read(editorb);
//								fis.close();
//								os.write(editorb);
//								os.flush();
//								break;
//							}else{
//								System.out.println("GET1:"+line);
//							}
//							//line = java.net.URLDecoder.decode(line,"UTF-8");
//							
//						}else if(line.equals("")){
//							break;
//						}
//					}else{
//						System.out.println("NEXT:"+line);
//						if(line.equals("")){
//							//os.write("HTTP/1.1 200 OK\n".getBytes("UTF-8"));
//							os.write("aaaa('OK')".getBytes("UTF-8"));
//							os.flush();
//							os.close();
//							break;
////							os.close();
////							ins.close();
//						}
//					}
//				}
				Map req = new HashMap();
				System.out.println("read off!");
				System.out.println("get:["+rstr+"]");
				if(rstr.startsWith("GET")){
					String[] rstrarr=rstr.split("\n");
					System.out.println("Len:"+rstrarr.length);
					System.out.println(rstrarr[0]); 
					String uri = rstrarr[0].split(" ")[1];
					String[] patt = uri.split("\\?");
					if(patt[0].equals("/editor.html")){
						System.out.println("uri");
						//os.write("HTTP/1.1 200 OK\n".getBytes("UTF-8"));
						File editor = new File(sssex.Activator.plugin_path+"kindeditor-4.1.10/examples/default.html");
						byte[] editorb = new byte[(int)editor.length()];
						FileInputStream fis = new FileInputStream(editor);
						fis.read(editorb);
						fis.close();
						os.write(editorb);
						os.flush();
						break;
					}else{
						System.out.println("GET1:"+rstrarr[0]);
					}
					String[] rurlarr=rstrarr[0].split(" ");
					for(int i=1;i<rstrarr.length-1;i++){
						req.put(rstrarr[i].split(": ")[0], rstrarr[i].split(": ")[1]);
					}
					String path = rurlarr[1];
					System.out.println(path);
				}
				os.write("function callback(ss){}".getBytes());
				String[] arr = rstr.split(" ");
				if(arr.length<=1){
					continue;
				}
				openfile="";
				bookmark = "";
				bookmarkfile = "";
				scope="";
				string = "";
				//rstr = rstr.split(" ")[1];
				//String param = rstr.substring(rstr.indexOf("?")+1);
			//	String[] params = param.split("&");
//				for(int i=0;i<params.length;i++){
//					String name = params[i].split("=")[0];
//					String vale = params[i].split("=")[1];
//                    vale = java.net.URLDecoder.decode(vale,"UTF-8");
//					if("scope".equals(name)){
//						scope = vale;
//					}
//					if("string".equals(name)){
//						string = vale;
//					}
//					if("bookmarkfile".equals(name)){
//						bookmarkfile = vale;
//						os.write(bookmarkfile.getBytes());
//					}
//					if("bookmark".equals(name)){
//						bookmark = vale;
//						os.write(bookmark.getBytes());
//					}
//					if("openfile".equals(name)){
//						openfile = vale;
//						os.write(openfile.getBytes());
//					}
//				}
				
				
				if(openfile!=null && !openfile.equals("")){
					Display.getDefault().syncExec(new Runnable() {
				         @SuppressWarnings("unused")
						public void run() {
							try{
								IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
								//获得文本编辑对象的document
								IDocument doc = ((ITextEditor)page.getActiveEditor()).getDocumentProvider().getDocument(page.getActiveEditor().getEditorInput());
								
								IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(openfile));
								System.out.println(file);
								IDE.openEditor(page, file);
							}catch(Throwable a ){
								a.printStackTrace();
							}
				         }
					});
				}
				
				// System.out.println("bookmark:"+bookmark);
				if(bookmark!=null && !bookmark.equals("")){
					 try{
						 String line = bookmark;
		        		 String[] markerSplit = null;
		        		 if(line!=null){
		        			 markerSplit= line.split("\\|");
		        			 if(markerSplit.length!=3){
		        				 break;
		        			 }
		        			 //System.out.println("line:"+line);
		        			 String resource = markerSplit[0];
		        			 String lineNumber = markerSplit[1];
		        			 String message = markerSplit[2];
		        			// System.out.println(resource);
			        		 IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(resource));
			        		// System.out.println(iresource);
				        	 try {
								IMarker imarker = iresource.createMarker(IMarker.BOOKMARK);
								imarker.setAttribute(IMarker.MESSAGE, message);
								imarker.setAttribute(IMarker.LINE_NUMBER, Integer.parseInt(lineNumber));
							 } catch (CoreException e) {
								e.printStackTrace();
							 }

		        		 }
					 }catch(Throwable a ){
					 }
				}
				
				if(bookmarkfile!=null && !bookmarkfile.equals("")){
					Display.getDefault().syncExec(new Runnable() {
				         public void run() {
				        	 
				        	 BufferedReader br = null;
				        	 try{
				        		 FileInputStream fis = new FileInputStream(bookmarkfile);
				        		 br = new BufferedReader(new InputStreamReader(fis));
					        	 String line = null;
					        	 while((line=br.readLine())!=null){
					        		 
					        		 String[] markerSplit = null;
					        		 if(line!=null){
					        			 markerSplit= line.split("\\|");
					        			 if(markerSplit.length!=3){
					        				 break;
					        			 }
					        			 //System.out.println("line:"+line);
					        			 String resource = markerSplit[0];
					        			 String lineNumber = markerSplit[1];
					        			 String message = markerSplit[2];
					        			// System.out.println(resource);
						        		 IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(resource));
						        		// System.out.println(iresource);
							        	 try {
											IMarker imarker = iresource.createMarker(IMarker.BOOKMARK);
											imarker.setAttribute(IMarker.MESSAGE, message);
											imarker.setAttribute(IMarker.LINE_NUMBER, Integer.parseInt(lineNumber));
										 } catch (CoreException e) {
											e.printStackTrace();
										 }
					        		 }
					        	 }
				        	 }catch(Exception ex){
				        		 ex.printStackTrace();
				        	 }finally{
				        		 if(br!=null){try {br.close();
								} catch (IOException e) {
									e.printStackTrace();
								}}
				        	 }
				        	 
				         }
					});     
				}
				
				if(scope!=null && !scope.equals("")){
					Display.getDefault().syncExec(new Runnable() {
				         public void run() {
				        	
				        	try{
				        	   TextSearchQueryProvider provider = TextSearchQueryProvider.getPreferred();
				        	   
				        	   System.out.println("provider:");
								try
								{   
									ISearchQuery query = createQuery(provider,scope,string);
									
									if (query != null)
										
										NewSearchUI.runQueryInBackground(query);
								}catch (Throwable e){  
									e.printStackTrace();
									//try{
									//	ErrorDialog.openError(getShell(), SearchMessages.RetrieverAction_error_title,
									//		SearchMessages.RetrieverAction_error_message, e.getStatus());
									//}catch(Exception ex){
									//	ex.printStackTrace();
									//}
								}
							    // searching end
				        	}catch(Exception ex){
				        		ex.printStackTrace();
				        	}
				    }
				 }
		      );
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
			finally{
				if(ins!=null){
					try {
						ins.close();
					} catch (IOException e) {
						 e.printStackTrace();
					}
				}
				if(os!=null){
					try {
						os.close();
					} catch (IOException e) {
						 e.printStackTrace();
					}
				}
				if(explor!=null){
					try {
						explor.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			}	
			
		}
	}
	
	@SuppressWarnings({ "unused", "restriction" })
	private Shell getShell(){
		return SearchPlugin.getActiveWorkbenchShell();
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException{
		String aaa = "{\"mlog\":{\"servicegrade\":\"3001\",\"stbfactoryname\":\"\",\"repeatflg\":0,\"optrfactoryname\":\"\",\"isdup\":0,\"mobilebuandvalue\":\"\",\"getdatatype\":\"0\",\"pointid\":\"\",\"isbugtemp\":\"\",\"customerintent\":\"6\",\"is_managevisit\":\"\",\"sub_org_id\":\"\",\"logidTemp\":0,\"crmoutxml\":\"\",\"electend_date\":null,\"crmquickservicetypes\":\"\",\"is_end\":\"\",\"accessaccount\":\"\",\"faulttypetwo\":\"\",\"strphenomena\":\"故障现象:丢包;\",\"callno\":\"\",\"outbindid\":0,\"statutype\":0,\"opername\":\"Yuan-CD\",\"isspecialprocess\":1,\"operator\":929,\"quickid\":0,\"faultcodeone\":\"\",\"faultlocalid\":10100,\"activeid\":\"1\",\"linktel\":\"11111111111\",\"isfast_timeout\":\"\",\"faultdate\":\"2016-07-22 18:01:16\",\"electorder_date\":null,\"autodiagnosecode\":\"\",\"regionFlag\":0,\"quickservice\":0,\"prefixreason\":\"\",\"crmcost_result\":\"\",\"contractno\":\"\",\"electorder_msg\":\"\",\"custmanagername\":\"\",\"repairtime\":\"\",\"regionFlagdesc\":\"城市\",\"buzi_type\":392,\"local_id\":0,\"sub_brand\":\"\",\"telephone\":\"\",\"phenomena\":\"467\",\"crmorder_date\":null,\"logid\":2421220,\"isTimerRunFaultWork\":\"0\",\"bigbugdescribe\":\"\",\"pastransfer\":\"0\",\"is_quickservicetimeout\":\"\",\"scanstate\":\"\",\"touchmethod\":\"\",\"adslaccount\":\"\",\"customersatis\":\"\",\"diagnosecode\":\"\",\"stepvalue\":\"\",\"scantime\":null,\"adslno\":\"\",\"quickservice_charge\":\"\",\"accessno\":\"\",\"stbmodel\":\"\",\"customertypevalue\":\"\",\"cust_service_grade\":0,\"quickserviceflag\":\"\",\"mobilebuandtext\":\"\",\"sn\":\"\",\"bigbugcode\":\"\",\"crmorder_no\":\"\",\"quickservice_type\":\"\",\"statusdate\":null,\"satisfy\":\"\",\"faultid\":\"\",\"optrmodel\":\"\",\"askaddress\":\"\",\"faulttype\":\"\",\"nightservice\":\"0\",\"bigbugflag\":\"\",\"isforce\":\"0\",\"crmorder_result\":\"\",\"quickservic_elect_type\":\"\",\"crmcost_date\":null,\"askcontent\":\"\",\"crmorderdeal_result\":\"\",\"linkman\":\"先生\",\"isvisitcustomers\":\"\",\"type_id\":3,\"crmcostdeal_result\":\"\",\"currentstatus\":1,\"operdate\":null,\"electoutxml\":\"\",\"reserve1\":\"0\",\"vcid\":2,\"region_id\":\"1\",\"is_warranty\":0,\"billno\":\"70997878\",\"quickservice_result\":\"\",\"faultflag\":\"\",\"quickservice_method\":\"\",\"crmcost_no\":\"\",\"accountno\":\"\",\"fasttype\":\"\",\"scancount\":0,\"crmorder_msg\":\"\",\"applyxml\":\"\",\"adslaccessno\":\"\",\"faultsource\":\"人工报障\",\"custname\":\"\",\"prefixreason_id\":-1,\"telaccount\":\"\",\"brand\":\"\",\"childlocalid\":0,\"fault_mark\":\"\",\"createdate\":null,\"isLongTime\":0,\"quickservicesource\":\"\",\"faultcodetwo\":\"\",\"jsonparam\":\"\",\"accessType\":\"0\",\"internettype\":\"\",\"crmcost_msg\":\"\",\"faultcode\":\"\",\"faultno\":\"催单测试\",\"memo\":\"主叫号码:11111111111,更改联系号码:11111111111,客户在电脑旁边接受辅导后,明确表示障碍未恢复;工作人员是否联系:是;用户要求更改预约时间为:2016-07-23 18:01:20;故障现象:丢包;\",\"cdmacodevalue\":\"0\",\"whichpath\":0,\"prefixreasondesc\":\"-1 \",\"finaltype\":\"\",\"bureauno\":\"0\",\"ordertime\":\"2016-07-23 18:01:20\",\"sendreason\":\"\",\"faulttypeone\":\"\",\"quickservice_name\":\"\",\"exeten1\":\"\",\"strflowno\":\"\",\"exeten2\":\"\",\"istemp\":0,\"warranty_date\":null,\"custmanagerno\":\"\",\"electorder_result\":\"\",\"statutypeflg\":\"\",\"createoper\":\"929\",\"exeten3\":\"\",\"diagnoflg\":\"\"},\"slog\":{\"opertype\":2,\"callingno\":\"\",\"islinked\":\"1\",\"linkman\":\"先生\",\"memo\":\"主叫号码:11111111111,更改联系号码:11111111111,客户在电脑旁边接受辅导后,明确表示障碍未恢复;工作人员是否联系:是;用户要求更改预约时间为:2016-07-23 18:01:20;故障现象:丢包;\",\"operatorid\":929,\"cdmacodevalue\":\"0\",\"faultsource\":\"人工报障\",\"opername\":\"Yuan-CD\",\"operdate\":null,\"linkno\":\"11111111111\",\"mlogid\":2421220,\"vcid\":2,\"customerintent\":\"6\",\"operorder\":1,\"prefixreason\":\"\",\"tongbustatus\":\"\",\"prefixreasonid\":-1,\"explain\":\"\",\"billno\":\"\",\"callflowno\":\"\"},\"askturntourge\":false,\"sb\":\"[70997878][主叫号码:11111111111,更改联系号码:11111111111,客户在电脑旁边接受辅导后,明确表示障碍未恢复;工作人员是否联系:是;用户要求更改预约时间为:2016-07-23 18:01:20;故障现象:丢包;][6]][\"}";

//		for(int i=0;i<4000;i++){
//			aaa += "a";
//		}
		System.out.println(aaa.length());
		System.out.println(aaa.getBytes("gbk").length);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected ISearchQuery createQuery(TextSearchQueryProvider provider,String scope, String string) throws CoreException
	{
		//IWorkspace resource = ResourcesPlugin.getWorkspace();
		//IProject project = resource.getRoot().getProject(scope);
		ArrayList list = new ArrayList();
		String[] scopes = scope.split(";");
		for(int i=0;i<scopes.length;i++){
			IResource iresource = ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(scopes[i]));
			if(iresource!=null && iresource.exists()){
				list.add(iresource);
			}
		}
		
		//FileTextSearchScope.newSearchScope((IResource[])list.toArray(new IResource[0]), new String[]{"txt","html"}, false);
		//if (project != null)
			return provider.createQuery(string,(IResource[])list.toArray(new IResource[0]));
		//else
		//	return provider.createQuery(string);
	}
}
